package com.xjscrm.console.service.customer.sys.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.mobile.collect.api.MicaTopics;
import com.uzai.mobile.collect.api.dto.MicaTriggerDto;
import com.uzai.mobile.collect.api.dto.trigger.MicaTriggerAppConfigChangeMsg;
import com.uzai.mobile.collect.api.enums.MicaTriggerType;
import com.xjscrm.common.annotation.MerId;
import com.xjscrm.common.entity.MerBaseConfig;
import com.xjscrm.common.entity.WwDevice;
import com.xjscrm.common.enums.DeviceTypeEnum;
import com.xjscrm.common.enums.MerConfigKeyEnum;
import com.xjscrm.common.enums.MerConfigTypeEnum;
import com.xjscrm.common.enums.RedisCacheKeyEnum;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.console.mapper.MerBaseConfigMapper;
import com.xjscrm.console.mapper.WwDeviceMapper;
import com.xjscrm.console.mq.producer.SendMsgProducer;
import com.xjscrm.console.param.sysconfig.AppFuctionConfigDto;
import com.xjscrm.console.param.sysconfig.SysBrandConfigDto;
import com.xjscrm.console.service.customer.sys.SysConfigService;
import com.xjscrm.console.vo.sysconfig.AppFuctionConfigVo;
import com.xjscrm.console.vo.sysconfig.SysBrandConfigVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 系统设置
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class SysConfigServiceImpl implements SysConfigService {

    Logger logger = LoggerFactory.getLogger(SysConfigServiceImpl.class);

    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WwDeviceMapper wwDeviceMapper;

    @Autowired
    private SendMsgProducer sendMsgProducer;

    /**
     * 查询品牌设置详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public SysBrandConfigVo findSysBrandConfig(@MerId Long merId){

        SysBrandConfigVo sysBrandConfigVo = new SysBrandConfigVo();

        //查询运营商品牌设置信息
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.SYS_BRAND_CONFIG.getValue());
        if(merBaseConfig != null ){
            sysBrandConfigVo =  JSONObject.parseObject(merBaseConfig.getVal(), SysBrandConfigVo.class);
        }
        return sysBrandConfigVo;
    }

    /**
     * 修改品牌设置详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sysBrandConfigDto
     * @return null
     */
    public void updateSysBrandConfig(SysBrandConfigDto sysBrandConfigDto){

        SysBrandConfigVo sysBrandConfigVo = new SysBrandConfigVo();
        BeanUtils.copyProperties(sysBrandConfigDto, sysBrandConfigVo);

        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(sysBrandConfigDto.getMerId(), MerConfigKeyEnum.SYS_BRAND_CONFIG.getValue());
        Integer now = DateUtil.getTime();
        //修改
        if (merBaseConfig != null){
            merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(sysBrandConfigVo)));
            merBaseConfig.setUpdateTime(now);
            merBaseConfigMapper.update(merBaseConfig);
        } else { //增加
            merBaseConfig = new MerBaseConfig();
            merBaseConfig.setId(IdWorker.getId());
            merBaseConfig.setMerId(sysBrandConfigDto.getMerId());
            merBaseConfig.setType(MerConfigTypeEnum.PRODUCTS.getValue());
            merBaseConfig.setKey(MerConfigKeyEnum.SYS_BRAND_CONFIG.getValue());
            merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(sysBrandConfigVo)));
            merBaseConfig.setCreateTime(now);
            merBaseConfig.setUpdateTime(now);
            merBaseConfigMapper.insert(merBaseConfig);
        }

        //保存到Redis当中
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.MER_BASE_CONFIG.getKey(), MerConfigKeyEnum.SYS_BRAND_CONFIG.getValue(), sysBrandConfigDto.getMerId()), Tools.getStrEmpty(JSONObject.toJSONString(sysBrandConfigVo)));
    }

    /**
     * 查询品牌设置详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public AppFuctionConfigVo findAppFuctionConfig(@MerId Long merId){

        AppFuctionConfigVo appFuctionConfigVo = new AppFuctionConfigVo();

        //查询运营商品牌设置信息
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(merId, MerConfigKeyEnum.APP_FUCTION_CONFIG.getValue());
        if(merBaseConfig != null ){
            appFuctionConfigVo =  JSONObject.parseObject(merBaseConfig.getVal(), AppFuctionConfigVo.class);
        }
        return appFuctionConfigVo;
    }

    /**
     * 修改品牌设置详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param appFuctionConfigDto
     * @return null
     */
    public void updateAppFuctionConfig(AppFuctionConfigDto appFuctionConfigDto){

        if (appFuctionConfigDto.getLoginPassword() == null || appFuctionConfigDto.getLoginPassword().toString().length() != 6) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "密码长度必须设置为6位数字");
        }

        AppFuctionConfigVo appFuctionConfigVo = new AppFuctionConfigVo();
        BeanUtils.copyProperties(appFuctionConfigDto, appFuctionConfigVo);

        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(appFuctionConfigDto.getMerId(), MerConfigKeyEnum.APP_FUCTION_CONFIG.getValue());
        Integer now = DateUtil.getTime();
        //修改
        if (merBaseConfig != null){
            merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(appFuctionConfigVo)));
            merBaseConfig.setUpdateTime(now);
            merBaseConfigMapper.update(merBaseConfig);
        } else { //增加
            merBaseConfig = new MerBaseConfig();
            merBaseConfig.setId(IdWorker.getId());
            merBaseConfig.setMerId(appFuctionConfigDto.getMerId());
            merBaseConfig.setType(MerConfigTypeEnum.PRODUCTS.getValue());
            merBaseConfig.setKey(MerConfigKeyEnum.APP_FUCTION_CONFIG.getValue());
            merBaseConfig.setVal(Tools.getStrEmpty(JSONObject.toJSONString(appFuctionConfigVo)));
            merBaseConfig.setCreateTime(now);
            merBaseConfig.setUpdateTime(now);
            merBaseConfigMapper.insert(merBaseConfig);
        }

        //保存到Redis当中
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.MER_BASE_CONFIG.getKey(), MerConfigKeyEnum.APP_FUCTION_CONFIG.getValue(), appFuctionConfigDto.getMerId()), Tools.getStrEmpty(JSONObject.toJSONString(appFuctionConfigVo)));


        //发送mq指令
        List<WwDevice> wwDeviceList = wwDeviceMapper.selectByMerId(appFuctionConfigDto.getMerId());
        if (wwDeviceList != null && !wwDeviceList.isEmpty()) {
            for (WwDevice wwDevice : wwDeviceList) {
                try {
                    MicaTriggerAppConfigChangeMsg micaTriggerAppConfigChangeMsg = new MicaTriggerAppConfigChangeMsg();
                    MicaTriggerAppConfigChangeMsg.ConfigItem configItem = new MicaTriggerAppConfigChangeMsg.ConfigItem();
                    configItem.setKey(String.format(RedisCacheKeyEnum.MER_BASE_CONFIG.getKey(), MerConfigKeyEnum.APP_FUCTION_CONFIG.getValue(), appFuctionConfigDto.getMerId()));
                    configItem.setValue(Tools.getStrEmpty(JSONObject.toJSONString(appFuctionConfigVo)));
                    configItem.setType(3);
                    configItem.setDesc("");
                    micaTriggerAppConfigChangeMsg.setConfigItemList(new ArrayList<>(Collections.singleton(configItem)));

                    MicaTriggerDto micaTriggerDto = MicaTriggerDto.newInstance(micaTriggerAppConfigChangeMsg, MicaTriggerType.TRIGGER_CONFIG_PUSH);
                    micaTriggerDto.setMerId(wwDevice.getMerId());
                    micaTriggerDto.setDeviceId(wwDevice.getDeviceId());
                    micaTriggerDto.setDeviceType(DeviceTypeEnum.DT_ANDROID_WORK_WECHAT_VALUE);
                    sendMsgProducer.pushMsg(micaTriggerDto, MicaTopics.WW_TRIGGER_TOPIC);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }




    }

}
